package com.shadow.utils
{
	import flash.utils.ByteArray;
	
	public class Scramble
	{
		private static var IV:uint = 146;
		private static var MAGIC:String = ":NORITOWN:NINJA";
		public function Scramble()
		{
			
		}
		/**
		 *编码 
		 * @param $src
		 * @return 
		 * 
		 */		
		public static function encrypt($src:String):ByteArray
		{
			$src = ($src + MAGIC);
			var baSrc:ByteArray = new ByteArray();
			var baCryptic:ByteArray = new ByteArray();
			baSrc.writeUTFBytes($src);
			baSrc.position = 0;
			baSrc.compress();
			baSrc.position = 0;
			var len:uint = baSrc.length;
			var val:uint = IV;
			var i:uint;
			while (i < len)
			{
				val = (val ^ baSrc.readUnsignedByte());
				val = (((val << 4) & 240) | ((val >> 4) & 15));
				baCryptic.writeByte(val);
				i++;
			};
			return (baCryptic);
		}
		/**
		 *解码 
		 * @param $src
		 * @return 
		 * 
		 */		
		public static function decrypt($src:ByteArray):String
		{
			var baPlain:ByteArray;
			var src:uint;
			$src.position = 0;
			var plain:String = "";
			var len:uint = $src.length;
			var val:uint = IV;
			baPlain = new ByteArray();
			var i:uint;
			while (i < len)
			{
				src = ($src.readUnsignedByte() & 0xFF);
				val = ((val ^ (((src << 4) & 240) | ((src >> 4) & 15))) & 0xFF);
				baPlain.writeByte(val);
				val = src;
				i++;
			};
			baPlain.position = 0;
			baPlain.uncompress();
			plain = baPlain.readMultiByte(baPlain.length, "utf-8");
			var magic_length:uint = MAGIC.length;
			if (plain.substr(-(magic_length)) != MAGIC)
			{
				return ("");
			};
			plain = plain.substr(0, (plain.length - magic_length));
			return (plain);
		}
	}
}